package com.softao.ming.gde.internal.core.launcher.tasks;

import java.io.File;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.softao.ming.gde.core.launcher.LauncherContext;
import com.softao.ming.gde.internal.core.GdeCore;

/**
 * Prepares for launching. This usually is the first step to be performed.
 * <p>
 * In further implementation, the validation of the settings may also be implemented here.
 */
public class PrepareTask extends AbstractLauncherTask {

	@Override
	public void perform(LauncherContext context, IProgressMonitor monitor)
			throws CoreException {
		monitor.subTask("Preparing the output...");

		String outputLocation = context.getSettings().getOutputLocation();
		File file = new File(outputLocation);
		if (file.exists()) {
			if (file.isFile()) {
				String msg = "File " + file + " is not a directory.";
				IStatus status = new Status(IStatus.ERROR, GdeCore.PLUGIN_ID, msg);
				throw new CoreException(status);
			}
			if (!deleteDir(file)) {
				String msg = "Can not delete folder: " + file;
				IStatus status = new Status(IStatus.ERROR, GdeCore.PLUGIN_ID, msg);
				throw new CoreException(status);
			}
		}
		
		if (!file.mkdirs()) {
			String msg = "Can not create folder: " + file;
			IStatus status = new Status(IStatus.ERROR, GdeCore.PLUGIN_ID, msg);
			throw new CoreException(status);
		}
		
		monitor.worked(1);
	}
	
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
    }

}
